package com.lu.springbootinit.bizmq;

import com.lu.springbootinit.common.ErrorCode;
import com.lu.springbootinit.constant.BiMQConstant;
import com.lu.springbootinit.exception.BusinessException;
import com.lu.springbootinit.manager.AiManager;
import com.lu.springbootinit.model.entity.Chart;
import com.lu.springbootinit.service.ChartService;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Slf4j
@Component
public class BiMessageConsumer {
    @Resource
    private ChartService chartService;

    @Resource
    private AiManager aiManager;

    @SneakyThrows
    @RabbitListener(queues = {BiMQConstant.BI_QUEUE_NAME}, ackMode = "MANUAL")
    public void receiveMessage(String message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) {
        log.info("开始消费");
        if(StringUtils.isBlank(message)){
            channel.basicNack(deliveryTag,false,false);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"消息为空");
        }
        long chartId = Long.parseLong(message);
        //先修改数据库记录改为在修改中
        Chart chart = chartService.getById(chartId);
        if(chart == null){
            channel.basicNack(deliveryTag,false,false);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"图表为空");
        }
        chart.setState("running");
        boolean b = chartService.updateById(chart);
        if(!b) {
            channel.basicNack(deliveryTag,false,false);
            chartService.handleChartError(chart.getId(), "更新图表运行状态失败");
            return;
        }
        //调用AI
        long biModelId = 1659171950288818178L;
        String result = aiManager.duChat(biModelId, buildUserInput(chart));
        String[] splits = result.split("【【【【【");
        if (splits.length < 3) {
            channel.basicNack(deliveryTag,false,false);
            chartService.handleChartError(chart.getId(), "更新图表成功状态失败");
            return;
        }
        String genChart = splits[1].trim();
        genChart = genChart.replaceAll("\"\\s+xAxis\"", "\"xAxis\"");
        genChart = genChart.replaceAll("\"\\s+yAxis\"", "\"yAxis\"");
        String genResult = splits[2].trim();

        chart.setGenResult(genResult);
        chart.setGenChart(genChart);
        chart.setState("succeed");
        b = chartService.updateById(chart);
        if(!b) {
            channel.basicNack(deliveryTag,false,false);
            chartService.handleChartError(chart.getId(), "更新图表成功状态失败");
        }
        log.info("ReceiveMessage message = {}", message);
        channel.basicAck(deliveryTag, false);
    }

    /**
     * 构建用户输入
     * @param chart
     * @return
     */
    private String buildUserInput(Chart chart) {
        String goal = chart.getGoal();
        String chartType = chart.getChartType();
        String csvData = chart.getChartData();
        //用户输入
        StringBuilder userInput = new StringBuilder();
        userInput.append("你是一个数据分析师，接下来我会给你我的数据和分析目标，请告诉我你的结论").append("\n");
        userInput.append("分析目标:").append("\n");
        String userGoal = goal;
        if (StringUtils.isNotBlank(chartType)) {
            userGoal += ",请使用：" + chartType + "图表类型";
        }
        userInput.append(userGoal).append("\n");
        userInput.append("数据:" + goal).append(csvData).append("\n");
        return userInput.toString();
    }

}